package server

import (
	"enjoy_wangyashuo/formdata"
	"enjoy_wangyashuo/internal/model/redis"
	"enjoy_wangyashuo/internal/model/user"
	"enjoy_wangyashuo/pkg"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

// 登录
func Login(data formdata.UserLogin) (formdata.Users, error) {
	u := user.User{
		Phone: data.Phone,
	}

	//查询用户手机号是否存在
	detail, err := u.UserDetail()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return formdata.Users{}, fmt.Errorf("用户不存在 >>%v", err)
	}
	if data.LoginType == "0" {
		//密码登录  //判断密码
		if !pkg.ComparePwd(detail.Password, data.Password) {
			fmt.Println(detail.Password + "-----" + data.Password)
			return formdata.Users{}, fmt.Errorf("手机号或密码错误 >>%v", data.Password)
		}
	} else {
		//短信验证码登录  //获取缓存放验证码
		key := "phone_:" + data.Phone + "_type" + data.CodeType
		val, _ := redis.GetRedisVal(key)
		fmt.Println("短信验证码", val.String())
		if val.Val() != data.Code {
			fmt.Println(val.Val() + "-----" + data.Code)
			return formdata.Users{}, errors.New("短信验证失败")
		}
		fmt.Println("短信验证验证码成功")
	}
	token, err := pkg.GetJwtToken(strconv.Itoa(int(detail.ID)))
	stu := formdata.Users{
		Phone:    detail.Phone,
		Img:      detail.Img,
		Username: detail.Username,
		Token:    token,
	}
	return stu, err
}

// 注册
func Register(data formdata.UserRegister) (string, error) {

	if !pkg.ValidatePhoneNumber(data.Phone) {
		return "", fmt.Errorf("手机号格式不正确")
	}
	fmt.Println("1111", data.Phone)
	encryptedPassword := pkg.Md5Encrypt(data.Password)
	// 检查手机号是否已存在
	res := user.User{
		Username: data.Username,
		Password: encryptedPassword,
		Phone:    data.Phone,
	}
	detail, err := res.UserDetail()
	// 先处理非记录不存在的错误（真正的服务器错误）
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return "", fmt.Errorf("服务器错误->%v", err)
	}
	// 判断手机号是否已注册
	if detail.ID != 0 {
		return "", fmt.Errorf("该手机号已被注册")
	}
	create, err := res.Create()
	if err != nil {
		return "", fmt.Errorf("注册失败")
	}
	return pkg.GetJwtToken(strconv.Itoa(int(create.ID)))
}

// 修改用户密码
func UpdatePasswordByUserId(data formdata.UpdateDara, userId int) error {
	pwd := pkg.Md5Encrypt(data.Password)
	u := user.User{
		Model: gorm.Model{
			ID: uint(userId),
		},
		Password: pwd,
		Phone:    data.Phone,
	}
	fmt.Println("密码是", pwd)
	key := "phone_:" + data.Phone + "_type:" + data.Password
	val, _ := redis.GetRedisVal(key)
	if val.Val() != data.Code {
		fmt.Println(val.Val() + "-----" + data.Code)
		return errors.New("短信验证失败")
	}
	fmt.Println("短信验证码成功")
	return u.UpdateDara()
}
